package com.whh.starter.web.cipher;

import cn.hutool.core.io.IoUtil;
import com.alibaba.fastjson.JSON;
import com.whh.starter.cipher.CipherService;
import com.whh.starter.config.DefaultCodeMapper;
import com.whh.starter.config.RequestContext;
import com.whh.starter.config.SystemException;
import com.whh.starter.config.annotation.ApiCipherDisable;
import com.whh.starter.properties.CipherProperties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.MethodParameter;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpInputMessage;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.util.StreamUtils;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.RequestBodyAdvice;

import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Type;
import java.util.List;

import static com.whh.starter.config.constant.CommonConstants.*;


@ControllerAdvice
public class DecryptRequestBody implements RequestBodyAdvice {
    private static final Logger log = LoggerFactory.getLogger(DecryptRequestBody.class);

    private final CipherService cipherService;
    private final CipherProperties cipherProperties;

    public DecryptRequestBody(CipherService cipherService, CipherProperties cipherProperties) {
        this.cipherService = cipherService;
        this.cipherProperties = cipherProperties;
    }

    @Override
    public boolean supports(MethodParameter methodParameter, Type targetType, Class<? extends HttpMessageConverter<?>> converterType) {

        return cipherProperties.allowRequestCipher() && (!methodParameter.hasMethodAnnotation(ApiCipherDisable.class) || !methodParameter.getContainingClass().isAnnotationPresent(ApiCipherDisable.class));
    }

    @Override
    public HttpInputMessage beforeBodyRead(HttpInputMessage inputMessage, MethodParameter parameter, Type targetType, Class<? extends HttpMessageConverter<?>> converterType) throws IOException {
        HttpHeaders headers = inputMessage.getHeaders();
        List<String> headKeys = headers.get(SECRET_KEY);
        if (headKeys == null || headKeys.isEmpty()) {
            throw new SystemException("请求头错误，缺失 secret_key", DefaultCodeMapper.SECRET_KEY_PARAM_ERROR);
        }
        String encryptSecretKey = headKeys.get(0);
        String secretKey = cipherService.asymmetricDecrypt(encryptSecretKey);
        RequestContext.getCurrentContext().secretKey(secretKey);
        String bodyString = StreamUtils.copyToString(inputMessage.getBody(), CHARSET);
        String encryptBody = JSON.parseObject(bodyString).getString(ENCRYPT_DATA_FILED);
        String body = cipherService.symmetricDecrypt(encryptBody,secretKey);

        //todo xss等
        Object o = JSON.parseObject(body, targetType);
        log.info("asd: {}",o);
        return new HttpInputMessage() {
            @Override
            public InputStream getBody() throws IOException {
                return IoUtil.toUtf8Stream(body);
            }

            @Override
            public HttpHeaders getHeaders() {
                return inputMessage.getHeaders();
            }
        };
    }

    @Override
    public Object afterBodyRead(Object body, HttpInputMessage inputMessage, MethodParameter parameter, Type targetType, Class<? extends HttpMessageConverter<?>> converterType) {
        return body;
    }

    @Override
    public Object handleEmptyBody(Object body, HttpInputMessage inputMessage, MethodParameter parameter, Type targetType, Class<? extends HttpMessageConverter<?>> converterType) {
        return null;
    }
}
